package edu.uwm.cs552;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

/**
 * A class for editing the board to set 
 * the location given as a particular terrain.
 */
class TerrainDraw implements HexBoardEditAction {
	private final Terrain terrain;
	private static ImageIcon[] icons;

	public TerrainDraw(Terrain t) {
		terrain = t;
	}
	
	public Terrain getTerrain() {
		return terrain;
	}
	
	public void apply(HexBoard hexBoard, Point p, double scale) {
		HexCoordinate h = HexCoordinate.fromPoint(p, scale);
		if (terrain == null) hexBoard.removeTerrain(h);
		else hexBoard.putTerrain(h,terrain);
	}
	
	public String getLabel() {
		return terrain == null ? "[Erase terrain]" : terrain.toString();
	}

	public ImageIcon getIcon() {
		final ImageIcon icon;
		ImageIcon[] icons = getTerrainIcons();
		if (terrain != null) {
			icon = icons[terrain.ordinal()];
		} else {
			icon = icons[Terrain.values().length];
		}
		return icon;
	}

	/**
	 * Return the (singleton) array of icons for terrains indexed by terrain ordinal.
	 * With one extra item at the end for blank icon.
	 * @return
	 */
	static ImageIcon[] getTerrainIcons() {
		if (TerrainDraw.icons == null) {
			ImageIcon[] result = new ImageIcon[Terrain.values().length+1];
			for (int i=0; i < result.length; ++i) {
				BufferedImage im = new BufferedImage(TerrainDraw.ICON_SIZE,TerrainDraw.ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
				Graphics g = im.getGraphics();
				g.translate(TerrainDraw.ICON_SIZE/2, TerrainDraw.ICON_SIZE/2);
				if (i < Terrain.values().length) {
					Terrain.values()[i].draw(g, HexCoordinate.ORIGIN, TerrainDraw.ICON_SIZE, true);
				}
				result[i] = new ImageIcon(im);
			}
			TerrainDraw.icons = result;
		}
		return TerrainDraw.icons;
	}
}